<template>
  <div class="shop-detail-container">
    <!-- 顶部统计卡片 -->
    <div class="stats-section">
      <div class="stat-card income-card">
        <div class="stat-icon">+</div>
        <div class="stat-content">
          <div class="stat-amount">+{{ formatAmount(totalIncome) }}</div>
          <div class="stat-label">入账金额</div>
          <div class="stat-desc">来自订单表</div>
        </div>
      </div>
      <div class="stat-card expense-card">
        <div class="stat-icon">-</div>
        <div class="stat-content">
          <div class="stat-amount">-{{ formatAmount(totalExpense) }}</div>
          <div class="stat-label">出账金额</div>
          <div class="stat-desc">来自售后表</div>
        </div>
      </div>
      <div class="stat-card net-card">
        <div class="stat-icon">¥</div>
        <div class="stat-content">
          <div class="stat-amount" :class="totalIncome - totalExpense >= 0 ? 'positive' : 'negative'">
            {{ totalIncome - totalExpense >= 0 ? '+' : '' }}{{ formatAmount(totalIncome - totalExpense) }}
          </div>
          <div class="stat-label">净收入</div>
          <div class="stat-desc">入账 - 出账</div>
        </div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form ref="queryRef" :model="queryParams" inline class="search-form">
        <el-form-item label="订单编号">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单编号"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="店铺名称">
          <el-input
            v-model="queryParams.storeName"
            placeholder="请输入店铺名称"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="账单类型">
          <el-select v-model="queryParams.billType" placeholder="请选择账单类型" clearable class="search-select">
            <el-option label="全部" value="" />
            <el-option label="下单" value="下单" />
            <el-option label="售后" value="售后" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="search-date"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" class="search-btn">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="syncAllDataToShopDetail" :loading="loading">
            <el-icon><Download /></el-icon>
            同步数据
          </el-button>
          <el-button type="warning" @click="handleExport">
            <el-icon><Upload /></el-icon>
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

        <!-- 交易明细列表 -->
    <div class="table-section">
      <div class="table-header">
        <div class="header-left">
          <span class="header-title">商家收支明细</span>
          <div class="header-tips">
            <el-tooltip content="下单类型：来自订单表，金额为正数（入账）" placement="top">
              <el-tag type="success" size="small">下单=入账</el-tag>
            </el-tooltip>
            <el-tooltip content="售后类型：来自售后表，金额为负数（出账）" placement="top">
              <el-tag type="danger" size="small">售后=出账</el-tag>
            </el-tooltip>
          </div>
        </div>
        <div class="header-stats">
          <span class="stat-item">
            总收入: <span class="income-text">+{{ formatAmount(totalIncome) }}</span>
            <small>(订单表)</small>
          </span>
          <span class="stat-item">
            总支出: <span class="expense-text">-{{ formatAmount(totalExpense) }}</span>
            <small>(售后表)</small>
          </span>
          <span class="stat-item">
            净收入: <span :class="totalIncome - totalExpense >= 0 ? 'income-text' : 'expense-text'">
              {{ totalIncome - totalExpense >= 0 ? '+' : '' }}{{ formatAmount(totalIncome - totalExpense) }}
            </span>
          </span>
        </div>
      </div>
      
      <el-table 
        v-loading="loading" 
        :data="shopDetailList" 
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="店铺名称" align="center" prop="storeName" min-width="120" show-overflow-tooltip />
        <el-table-column label="订单编号" align="center" prop="orderNo" min-width="140" show-overflow-tooltip />
        <el-table-column label="账单类型" align="center" prop="billType" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.billType === '下单' ? 'success' : 'danger'">
              {{ scope.row.billType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="记录消息" align="center" prop="recordMsg" min-width="200" show-overflow-tooltip />
        <el-table-column label="金额(元)" align="center" width="140">
          <template #default="scope">
            <div>
              <span :style="{ 
                color: scope.row.billType === '下单' ? '#67c23a' : '#f56c6c',
                fontWeight: 'bold',
                fontSize: '14px'
              }">
                {{ scope.row.billType === '下单' ? '+' : '-' }}{{ Math.abs(parseFloat(scope.row.amount)) }}
              </span>
            </div>
            <div style="font-size: 10px; color: #909399; margin-top: 2px;">
              {{ scope.row.billType === '下单' ? '订单收入' : '售后退款' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="支付时间" align="center" prop="payTime" width="160" show-overflow-tooltip />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" show-overflow-tooltip />
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
              {{ scope.row.status === 1 ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-wrapper">
      <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup name="ShopDetail">
import { listShopDetail, getShopDetail, addShopDetail, updateShopDetail } from "@/api/order/shopDetail.js"
import { listAfterSales } from "@/api/order/afterSales.js"
import { listOrders } from "@/api/order/orders.js"
import { listShop } from "@/api/order/shop.js"
import { toRaw } from "vue"
import { Search, Refresh, Download, Upload } from '@element-plus/icons-vue'
const { proxy } = getCurrentInstance()
const shopDetailList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tenantId: null,
    storeName: null,
    billType: null,
    amount: null,
    currency: null,
    recordMsg: null,
    orderNo: null,
    tradeNo: null,
    payTime: null,
    refundTime: null,
    status: null,
    extra: null,
    createdAt: null,
    updatedAt: null
  }

})

const { queryParams, form } = toRefs(data)

// 新增响应式数据
const dateRange = ref([])
const totalIncome = ref(0)
const totalExpense = ref(0)
const shopDetailListAll = ref([])
// 用于存储当前查询条件的统计数据
const currentQueryStats = ref({
  income: 0,
  expense: 0,
  isInitialLoad: true
})

// 用于记录上次查询条件，判断是否发生变化
const lastQueryConditions = ref({})

// 标记是否需要重新计算统计数据
const needRecalculateStats = ref(true)

/** 查询商家收支明细列表 */
function getList() {
  loading.value = true
  console.log('发送查询请求，参数:', JSON.parse(JSON.stringify(queryParams.value)))
  
  listShopDetail(queryParams.value).then(response => {
    shopDetailList.value = response.rows
    console.log("获取的商家明细列表数据", response.rows?.length || 0, "条记录")
    console.log("查询结果详情:", JSON.parse(JSON.stringify(toRaw(shopDetailList.value))))
    total.value = response.total
    loading.value = false
    
    // 只在首次加载或查询条件改变时计算统计数据
    if (needRecalculateStats.value) {
      console.log('需要重新计算统计数据，当前页码:', queryParams.value.pageNum)
      calculateStatsForCurrentQuery()
      needRecalculateStats.value = false
    } else {
      console.log('不需要重新计算统计数据，仅更新列表，当前页码:', queryParams.value.pageNum)
    }
  }).catch(error => {
    console.error('查询失败:', error)
    loading.value = false
    proxy.$modal.msgError('查询失败，请重试')
  })
}

/** 获取当前查询条件下的所有数据用于统计 */
async function calculateStatsForCurrentQuery() {
  try {
    // 获取当前查询条件下的所有数据（不分页）
    const allDataParams = {
      ...queryParams.value,
      pageNum: 1,
      pageSize: 9999
    }
    
    const response = await listShopDetail(allDataParams)
    const allData = response.rows || []
    
    let income = 0
    let expense = 0
    
    allData.forEach(item => {
      const amount = parseFloat(item.amount) || 0
      if (item.billType === '下单') {
        income += Math.abs(amount)
      } else if (item.billType === '售后') {
        expense += Math.abs(amount)
      }
    })
    
    // 更新统计数据
    totalIncome.value = income
    totalExpense.value = expense
    
    // 记录当前查询条件的统计
    currentQueryStats.value = {
      income,
      expense,
      isInitialLoad: false
    }
    
    // 保存当前查询条件
    lastQueryConditions.value = JSON.parse(JSON.stringify(queryParams.value))
    
    console.log(`当前查询条件统计 - 入账: ${income}, 出账: ${expense}`)
  } catch (error) {
    console.error('计算统计数据失败:', error)
  }
}

/** 检查查询条件是否发生变化 */
function isQueryConditionChanged() {
  // 如果是首次加载，认为条件发生了变化
  if (Object.keys(lastQueryConditions.value).length === 0) {
    return true
  }
  
  const currentConditions = {
    orderNo: queryParams.value.orderNo || null,
    storeName: queryParams.value.storeName || null,
    billType: queryParams.value.billType || null,
    startDate: queryParams.value.startDate || null,
    endDate: queryParams.value.endDate || null
  }
  
  const lastConditions = {
    orderNo: lastQueryConditions.value.orderNo || null,
    storeName: lastQueryConditions.value.storeName || null,
    billType: lastQueryConditions.value.billType || null,
    startDate: lastQueryConditions.value.startDate || null,
    endDate: lastQueryConditions.value.endDate || null
  }
  
  const isChanged = JSON.stringify(currentConditions) !== JSON.stringify(lastConditions)
  console.log('查询条件比较:', {
    current: currentConditions,
    last: lastConditions,
    changed: isChanged
  })
  
  return isChanged
}

const orderList = ref([])
const afterSalesList = ref([])
const shopList = ref([])

/**
 * 获取所有相关数据
 */
async function getAllRelatedData() {
  try {
    const [ordersResponse, afterSalesResponse, shopResponse] = await Promise.all([
      listOrders({ pageNum: 1, pageSize: 9999 }),
      listAfterSales({ pageNum: 1, pageSize: 9999 }),
      listShop({ pageNum: 1, pageSize: 9999 })
    ])
    
    orderList.value = ordersResponse.rows
    afterSalesList.value = afterSalesResponse.rows
    shopList.value = shopResponse.rows
    
    console.log("获取的订单列表数据", orderList.value)
    console.log("获取的售后列表数据", afterSalesList.value)
    console.log("获取的店铺列表数据", shopList.value)
  } catch (error) {
    console.error("获取相关数据失败:", error)
    proxy.$modal.msgError("获取数据失败")
  }
}

/**
 * 根据店铺ID获取店铺名称
 */
function getShopNameById(shopId) {
  const shop = shopList.value.find(s => s.shopId === shopId)
  return shop ? shop.shopName : '未知店铺'
}

/**
 * 同步订单数据到商家收支明细表 - 来源：订单表，类型：下单，金额：正数（入账）
 */
async function syncOrdersToShopDetail(silent = false) {
  try {
    if (!silent) loading.value = true
    let addCount = 0
    let updateCount = 0
    let errorCount = 0

    for (const order of orderList.value) {
      try {
        // 基本数据验证
        if (!order || !order.orderNo) {
          console.warn('订单数据不完整，跳过:', order)
          continue
        }

        // 只处理已支付的订单 (order_status >= 2)
        if (order.orderStatus < 2) continue

        // 检查是否已存在（需要重新获取最新数据来判断）
        const currentShopDetailResponse = await listShopDetail({ 
          pageNum: 1, 
          pageSize: 9999, 
          orderNo: order.orderNo, 
          billType: '下单' 
        })
        const existingItem = currentShopDetailResponse.rows && currentShopDetailResponse.rows.length > 0 
          ? currentShopDetailResponse.rows[0] 
          : null

        // 确保金额为正数（入账金额）
        const incomeAmount = Math.abs(order.businessIncome || order.realPrice || 0)
        
        // 验证金额
        if (incomeAmount <= 0) {
          console.warn(`订单 ${order.orderNo} 金额无效，跳过同步`)
          continue
        }

        const shopDetailData = {
          tenantId: order.tenantId || 1,
          storeName: getShopNameById(order.shopId),
          billType: '下单', // 来自订单表，类型为下单
          amount: incomeAmount, // 正数，表示入账
          currency: 'CNY',
          recordMsg: `订单收入 - 订单号${order.orderNo} - 商家实际收入`,
          orderNo: order.orderNo,
          tradeNo: order.tradeNo || '',
          // 不发送日期字段，让后端自动处理
          status: 1,
          extra: JSON.stringify({
            dataSource: 'orders', // 标记数据来源
            orderId: order.orderId,
            orderStatus: order.orderStatus,
            realPrice: order.realPrice,
            businessIncome: order.businessIncome,
            originalCreateTime: order.orderCreateTime,
            originalPayTime: order.payTime
          })
        }

        if (existingItem) {
          // 更新现有记录
          console.log(`订单 ${order.orderNo} 已存在收支明细，进行更新操作`)
          shopDetailData.id = existingItem.id
          await updateShopDetail(shopDetailData)
          updateCount++
        } else {
          // 新增记录
          console.log(`订单 ${order.orderNo} 不存在收支明细，进行新增操作`)
          await addShopDetail(shopDetailData)
          addCount++
        }
      } catch (error) {
        console.error(`处理订单 ${order.orderNo} 失败:`, error)
        errorCount++
      }
    }

    if (!silent) {
      proxy.$modal.msgSuccess(`订单同步完成：新增${addCount}条，更新${updateCount}条，失败${errorCount}条`)
    } else {
      console.log(`订单同步完成：新增${addCount}条，更新${updateCount}条，失败${errorCount}条`)
    }
  } catch (error) {
    console.error("同步订单数据失败:", error)
    if (!silent) proxy.$modal.msgError("订单数据同步失败")
  } finally {
    if (!silent) loading.value = false
  }
}

/**
 * 同步售后数据到商家收支明细表 - 来源：售后表，类型：售后，金额：负数（出账）
 */
async function syncAfterSalesToShopDetail(silent = false) {
  try {
    if (!silent) loading.value = true
    let addCount = 0
    let updateCount = 0
    let errorCount = 0

    for (const afterSales of afterSalesList.value) {
      try {
        // 基本数据验证
        if (!afterSales || !afterSales.afterSalesId) {
          console.warn('售后数据不完整，跳过:', afterSales)
          continue
        }

        // 只处理已完成退款的售后单
        if (!afterSales.refundTime) continue

        // 查找对应的订单信息
        const relatedOrder = orderList.value.find(order => order.orderId === afterSales.orderId)
        if (!relatedOrder || !relatedOrder.orderNo) {
          console.warn(`售后单 ${afterSales.afterSalesId} 找不到对应订单，跳过`)
          continue
        }

        // 检查是否已存在（需要重新获取最新数据来判断）
        const currentShopDetailResponse = await listShopDetail({ 
          pageNum: 1, 
          pageSize: 9999, 
          orderNo: relatedOrder.orderNo, 
          billType: '售后' 
        })
        const existingItem = currentShopDetailResponse.rows && currentShopDetailResponse.rows.length > 0 
          ? currentShopDetailResponse.rows[0] 
          : null

        // 确保金额为负数（出账金额）
        const expenseAmount = -Math.abs(afterSales.refundPrice || 0)
        
        // 验证金额
        if (Math.abs(expenseAmount) <= 0) {
          console.warn(`售后单 ${afterSales.afterSalesId} 退款金额无效，跳过同步`)
          continue
        }

        const shopDetailData = {
          tenantId: relatedOrder.tenantId || 1,
          storeName: getShopNameById(relatedOrder.shopId),
          billType: '售后', // 来自售后表，类型为售后
          amount: expenseAmount, // 负数，表示出账
          currency: 'CNY',
          recordMsg: `售后退款 - ${afterSales.afterSalesReason || '退款'} - 订单号${relatedOrder.orderNo}`,
          orderNo: relatedOrder.orderNo,
          tradeNo: afterSales.tradeNo || '',
          // 不发送日期字段，让后端自动处理
          status: 1,
          extra: JSON.stringify({
            dataSource: 'after_sales', // 标记数据来源
            afterSalesId: afterSales.afterSalesId,
            afterSalesType: afterSales.afterSalesType,
            refundType: afterSales.refundType,
            refundPrice: afterSales.refundPrice,
            afterSalesReason: afterSales.afterSalesReason,
            originalApplyTime: afterSales.applyTime,
            originalRefundTime: afterSales.refundTime
          })
        }

        if (existingItem) {
          // 更新现有记录
          console.log(`售后单 ${afterSales.afterSalesId} (订单${relatedOrder.orderNo}) 已存在收支明细，进行更新操作`)
          shopDetailData.id = existingItem.id
          await updateShopDetail(shopDetailData)
          updateCount++
        } else {
          // 新增记录
          console.log(`售后单 ${afterSales.afterSalesId} (订单${relatedOrder.orderNo}) 不存在收支明细，进行新增操作`)
          await addShopDetail(shopDetailData)
          addCount++
        }
      } catch (error) {
        console.error(`处理售后单 ${afterSales.afterSalesId} 失败:`, error)
        errorCount++
      }
    }

    if (!silent) {
      proxy.$modal.msgSuccess(`售后同步完成：新增${addCount}条，更新${updateCount}条，失败${errorCount}条`)
    } else {
      console.log(`售后同步完成：新增${addCount}条，更新${updateCount}条，失败${errorCount}条`)
    }
  } catch (error) {
    console.error("同步售后数据失败:", error)
    if (!silent) proxy.$modal.msgError("售后数据同步失败")
  } finally {
    if (!silent) loading.value = false
  }
}

/**
 * 批量同步所有数据
 */
async function syncAllDataToShopDetail() {
  try {
    loading.value = true
    console.log('开始手动同步数据...')
    
    // 1. 获取所有相关数据（订单、售后、店铺）
    console.log('正在获取最新的订单、售后、店铺数据...')
    await getAllRelatedData()
    console.log('获取相关数据完成')
    
    // 2. 同步订单数据（会自动检查是否已存在）
    console.log('开始同步订单数据...')
    await syncOrdersToShopDetail(false)
    
    // 3. 同步售后数据（会自动检查是否已存在）
    console.log('开始同步售后数据...')
    await syncAfterSalesToShopDetail(false)
    
    // 4. 重新加载商家收支明细数据并重新计算统计
    console.log('重新加载收支明细数据...')
    needRecalculateStats.value = true // 同步数据后需要重新计算统计
    await getList()
    
    proxy.$modal.msgSuccess("数据同步完成！已根据订单号和账单类型进行去重处理")
  } catch (error) {
    console.error("批量同步失败:", error)
    proxy.$modal.msgError(`数据同步失败: ${error.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}



// function listAll() {
//   listShopDetail(queryParams.value).then(response => {
//     shopDetailListAll.value = response.rows
//     console.log("获取的列表数据",JSON.parse(JSON.stringify(toRaw(shopDetailListAll.value))),"listall")
//     calculateStats()
//     console.log(totalIncome,"totalincom")
//   })
// }
/** 计算统计数据（已废弃，使用 calculateStatsForCurrentQuery 替代） */
function calculateStats() {
  // 这个函数已被 calculateStatsForCurrentQuery 替代
  // 保留是为了兼容性，实际不再使用
}

/** 格式化金额显示 */
function formatAmount(amount) {
  return amount.toFixed(2)
}



// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    tenantId: null,
    storeName: null,
    billType: null,
    amount: null,
    currency: null,
    recordMsg: null,
    orderNo: null,
    tradeNo: null,
    createTime: null,
    payTime: null,
    refundTime: null,
    status: null,
    extra: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("shopDetailRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  
  // 处理日期范围查询
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.startDate = dateRange.value[0]
    queryParams.value.endDate = dateRange.value[1]
  } else {
    queryParams.value.startDate = null
    queryParams.value.endDate = null
  }
  
  console.log('执行查询，当前查询参数:', JSON.parse(JSON.stringify(queryParams.value)))
  
  // 检查查询条件是否发生变化，如果变化则需要重新计算统计数据
  if (isQueryConditionChanged()) {
    needRecalculateStats.value = true
    console.log('查询条件发生变化，将重新计算统计数据')
  } else {
    console.log('查询条件未发生变化，不重新计算统计数据')
  }
  
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  dateRange.value = []
  
  // 手动清空查询参数
  queryParams.value.orderNo = null
  queryParams.value.storeName = null
  queryParams.value.billType = null
  queryParams.value.startDate = null
  queryParams.value.endDate = null
  
  // 重置操作相当于查询条件变化，需要重新计算统计数据
  needRecalculateStats.value = true
  console.log('重置查询条件，将重新计算统计数据')
  
  handleQuery()
}

/** 分页大小改变 */
function handleSizeChange(val) {
  queryParams.value.pageSize = val
  // 分页大小改变不需要重新计算统计数据，只是改变显示条数
  getList()
}

/** 当前页改变 */
function handleCurrentChange(val) {
  queryParams.value.pageNum = val
  // 页码改变不需要重新计算统计数据，只是改变显示页面
  getList()
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/shopDetail/export', {
    ...queryParams.value
  }, `shopDetail_${new Date().getTime()}.xlsx`)
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// 页面初始化
onMounted(async () => {
  try {
    loading.value = true
    console.log('开始页面初始化...')
    
    // 首次进入页面，标记需要计算统计数据
    needRecalculateStats.value = true
    currentQueryStats.value.isInitialLoad = true
    
    // 只加载现有的商家收支明细数据，不进行自动同步
    await getList()
    console.log('页面初始化完成，已加载现有商家收支明细数据和统计信息')
    
  } catch (error) {
    console.error('页面初始化失败:', error)
    proxy.$modal.msgError('页面加载失败，请刷新重试')
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.shop-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 顶部统计卡片 */
.stats-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 24px;
  color: white;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.income-card {
  background: linear-gradient(135deg, #00c9ff 0%, #92fe9d 100%);
}

.expense-card {
  background: linear-gradient(135deg, #fc466b 0%, #3f5efb 100%);
}

.net-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon {
  font-size: 36px;
  font-weight: bold;
  margin-right: 20px;
  opacity: 0.8;
}

.stat-content {
  flex: 1;
}

.stat-amount {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-amount.positive {
  color: #ffffff;
}

.stat-amount.negative {
  color: #ffcccb;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 2px;
}

.stat-desc {
  font-size: 12px;
  opacity: 0.7;
}

/* 搜索区域 */
.search-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.search-input {
  width: 180px;
}

.search-select {
  width: 140px;
}

.search-date {
  width: 240px;
}

.search-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  padding: 8px 20px;
}

.search-form .el-button {
  margin-left: 8px;
}

/* 表格区域 */
.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-tips {
  display: flex;
  gap: 8px;
  align-items: center;
}

.header-stats {
  display: flex;
  gap: 20px;
  align-items: center;
}

.stat-item {
  font-size: 14px;
  color: #606266;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.stat-item small {
  font-size: 10px;
  color: #909399;
}

.income-text {
  color: #67c23a;
  font-weight: bold;
}

.expense-text {
  color: #f56c6c;
  font-weight: bold;
}

.transaction-items {
  min-height: 400px;
}

.transaction-item {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.transaction-item:hover {
  background-color: #f8f9fa;
}

.transaction-item:last-child {
  border-bottom: none;
}

.item-left {
  flex: 0 0 200px;
}

.store-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.bill-type {
  font-size: 12px;
  color: #909399;
  background: #f0f2f5;
  padding: 2px 8px;
  border-radius: 4px;
  display: inline-block;
}

.item-center {
  flex: 1;
  padding: 0 20px;
}

.record-msg {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
  line-height: 1.4;
}

.create-time {
  font-size: 12px;
  color: #909399;
}

.item-right {
  flex: 0 0 120px;
  text-align: right;
}

.amount {
  font-size: 16px;
  font-weight: 600;
}

.amount.positive {
  color: #67c23a;
}

.amount.negative {
  color: #f56c6c;
}

/* 分页 */
.pagination-wrapper {
  padding: 20px;
  text-align: center;
  border-top: 1px solid #ebeef5;
  background: #fafafa;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .stats-section {
    flex-wrap: wrap;
  }
  
  .stat-card {
    min-width: 300px;
  }
}

@media (max-width: 768px) {
  .stats-section {
    flex-direction: column;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .search-select,
  .search-date {
    width: 100%;
  }
  
  .transaction-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .item-left,
  .item-center,
  .item-right {
    flex: none;
    width: 100%;
  }
  
  .item-right {
    text-align: left;
  }
}

/* Element Plus 样式覆盖 */
:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-date-editor.el-input) {
  border-radius: 6px;
}

:deep(.el-pagination) {
  justify-content: center;
}
</style>
